package com.zhou.controller;

import com.zhou.pojo.PageResult;
import com.zhou.pojo.Register;
import com.zhou.pojo.Result;
import com.zhou.service.EurekaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/server")
public class EurekaController {
    @Autowired
    private EurekaService eurekaService;


    @RequestMapping("/webPage")
    public String test() {
        return "main";
    }

    @RequestMapping("/child")
    public String GetChild() {
        return "child";
    }

    /**
     * 注册服务
     *
     * @param register
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    public Result add(@RequestBody Register register) {
        if (register == null || "".equals(register.getIp())) {
            System.out.println("add 中Register 为null");
            return new Result(false, "请写入数据");
        }
        //现在时间
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        register.setStatus(time);

        eurekaService.saveUser(register);
        return new Result(true, "注册服务成功");
    }

    /**
     * 心跳服务
     *
     * @param register
     */
    @RequestMapping("/edit")
    @ResponseBody
    public Result edit(@RequestBody Register register) {

        eurekaService.update(register);
        return new Result(true, "心跳服务更新成功");
    }

    /**
     * 拉取服务
     *
     * @return
     */
    @RequestMapping("/findAll")
    @ResponseBody
    public PageResult findAll() {
        List<Register> registers = eurekaService.findAll();
        int total = registers.size();
        return new PageResult((long) total, registers);
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Result delete(Integer id) {
        eurekaService.delete(id);
        return new Result(true, "删除成功");
    }

    @RequestMapping("/findById")
    @ResponseBody
    public Result findById(Integer id) {
        Register register = eurekaService.findById(id);

        return new Result(true, "回显数据成功", register);
    }
}
